package org.lonetree.tc.webapp.actions;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.lonetree.tc.core.Course;
import org.lonetree.tc.core.Course.CourseId;
import org.lonetree.tc.core.dao.CourseDAO;
import org.lonetree.tc.core.dao.DAOFactory;
import org.lonetree.tc.core.search.CourseCriteria;

;

public class SearchCourse extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		try {

			DAOFactory factory = DAOFactory
					.getDAOFactory(DAOFactory.FactoryImplementation.DB_DAO_FACTORY);
			CourseDAO cdao = factory.getCourseDAO();
			
			String dept = nullAndTrim(request.getParameter("dept"));
			String number = nullAndTrim(request.getParameter("number"));
			String title = nullAndTrim(request.getParameter("title"));
			
			if(dept == null && number == null && title == null)
				throw new RuntimeException("Please enter at least one search criterion.");
			
			CourseCriteria criteria = new CourseCriteria(dept, number, title);
			
			Set<Course> results = cdao.findCourses(criteria);
			request.setAttribute("courses", results);
			return mapping.findForward("success");
			
		} catch (Exception e) {
			request.setAttribute("message", e.getMessage());
			return mapping.findForward("failure");
		}
	}
	
	private static String nullAndTrim(String s){
		if(s == null)
			return s;
		
		s = s.trim();
		if(s.equals(""))
			return null;
		else
			return s;
	}
}